using System;
using RomanJendrusz.Amazon.ETL.Domain;
using RomanJendrusz.Amazon.ETL.Infrastructure.Loging.Core;
using RomanJendrusz.Amazon.ETL.Repositories;
using RomanJendrusz.Amazon.ETL.Services;
using System.Collections.Generic;

namespace RomanJendrusz.Amazon.ETL.Tasks
{
    public class CustomerReviewTask
    {
        private IBookService bookService;
        private IUnitOfWork unitOfWork;
        private IList<Book> booksChecked;

        public CustomerReviewTask(IBookService bookService, IUnitOfWork unitOfWork)
        {
            this.bookService = bookService;
            this.unitOfWork = unitOfWork;
            booksChecked = new List<Book>();
        }

        public void RetrieveReviewsFor(Book book)
        {
            if (book == null) throw new ArgumentNullException("book");
            if(booksChecked.Contains(book))
            {
                LogGateway.LogFor(GetType()).Warn(string.Format("Customer reviews informations for book {0} with asin {1} were allready retrieved", book.Title, book.Asin));
                return;
            }
            if(book.Updated > AmazonConstants.OlderEntityDate)
            {
                LogGateway.LogFor(GetType()).Warn(string.Format("Customer reviews for book {0} with asin {1} were retrieved earlier then the update entity date", book.Title, book.Asin));
                return;
            }
            LogGateway.LogFor(GetType()).Warn(string.Format("Retrieving customer reviews informations for book {0} with asin {1}", book.Title, book.Asin));
            var booksReviews = bookService.GetBookReviewsFor(book);
            AmazonCounters.CustomerReviewsRetrieved += booksReviews.Count;
            var reviews = new List<CustomerReview>();
            foreach(var review in booksReviews)
            {
                 reviews.Add(unitOfWork.CustomerReviewRepository.AttachIfAllreadyExists(review));
            }
            book.CustomerReviews.AddRange(reviews);
            booksChecked.Add(book);
            unitOfWork.SubmitChanges();
        }
    }
}